package com.itboye.mengwu.buy.ui;

import java.text.SimpleDateFormat;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ParseDouble;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.ui.aiwujia.ShenQingXinXiTianXieActivity;
import com.itboye.mengwu.app.ui.main.PingLunBaoBeiActivity;
import com.itboye.mengwu.app.ui.mymeng.ActivityShenQingShouHou;
import com.itboye.mengwu.app.ui.mymeng.ActivityTuiHuo;
import com.itboye.mengwu.app.ui.mymeng.ActivityTuiKuan;
import com.itboye.mengwu.app.ui.web.WebActivity;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.OrderDetailBean;
import com.itboye.mengwu.data.model.OrderQueryModel.OrderList;
import com.itboye.mengwu.data.model.StoreFavourableBean;
import com.itboye.mengwu.data.presenter.OrderPresenter;

public class DaiFuKuanDetail extends BaseActivity implements Observer {
	String orderId;
	OrderPresenter orderPresenter;
	OrderDetailBean orderDetailBean;
	TextView shengyutime, mobile, txt_reciever, address, goods_num,
			total_price, yunfei, orderNo, finalJiage, yunfei2, setUpTime,
			txt_title;
	Button btn_1, btn_2, btn_3, btn_4, btn_5;
	LinearLayout goods_container;
	String uid, orderCode;
	TextView dengdaipingjia;// 买家付款状态
	String type;
	TextView jiaoyi_status;// 交易状态
	RelativeLayout daishouhuo;// 待收货布局
	TextView kuaidistatus;// 快递状态
	ImageView back;
	LinearLayout zhifu;
	private TextView youhuiquan;
	private TextView hongbao, dianpu;
	StoreFavourableBean storeBean;
	TextView zhifubao_txt;
	private TextView zhifubaozhifu;
	private TextView yuezhifu, shifukuan;
	private TextView goodstotalprice;
	double goodsPrice;
	TextView lianxikefu;// 联系客服
	RelativeLayout mobile_rel;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_daifukuandetail;
	}

	@Override
	public void onMyCreate() {
		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		txt_title.setText("订单详情");
		showProgressDialog("数据拉取中，请稍后", true);
		orderId = getIntent().getStringExtra("id");
		type = getIntent().getStringExtra("type");
		orderPresenter = new OrderPresenter(this);
		orderPresenter.getXiangQing(orderId);

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_1.setOnClickListener(new OnClickListener() {// 1.去支付 3、退货 6、申请售后

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (type.equals("1")) {
					Intent intent = new Intent(DaiFuKuanDetail.this,
							PayTypeActivity.class);
					intent.putExtra("orderCode", orderCode);
					intent.putExtra("price", shifukuan.getTag().toString());
					intent.putExtra("desc", orderDetailBean.getStoreDesc());
					startActivity(intent);
					finish();
				} else if (type.equals("3")) {
					goToTuiHuo();
				} else if (type.equals("6")) {
					goToShouHou();
				}
			}
		});
		btn_4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (type.equals("1")) {// 去支付
					goToPayActivity();
				} else if (type.equals("3")) {// 申请售后
					goToShouHou();
				} else if (type.equals("6")) {// 评价
					Intent intent = new Intent(DaiFuKuanDetail.this,
							PingLunBaoBeiActivity.class);
					intent.putExtra("model", (OrderList) getIntent()
							.getSerializableExtra("model"));
					startActivity(intent);
				}
			}
		});
		btn_3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (type.equals("1")) {// 取消订单
					ByAlert.alert("取消订单");
					OrderBean model = new OrderBean();
					model.setCode(orderCode);
					model.setUid(uid);
					orderPresenter.delete(model);
				} else if (type.equals("3") || type.equals("6")) {// 查看物流
					goToWebActivity();
				}
			}
		});
		btn_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (type.equals("3")) {// 退款
					goToTuiKuan();
				} else if (type.equals("6")) {// 申请售后
					goToShouHou();
				}

			}
		});
	}

	/**
	 * 跳转申请售后
	 */
	protected void goToShouHou() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, ActivityShenQingShouHou.class);
		intent.putExtra("model", orderDetailBean);
		startActivity(intent);
	}

	/**
	 * 退货
	 */
	protected void goToTuiHuo() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, ActivityTuiHuo.class);
		intent.putExtra("model", orderDetailBean);
		startActivity(intent);
	}

	/**
	 * tui kuan
	 */
	protected void goToTuiKuan() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, ActivityTuiKuan.class);
		intent.putExtra("model", orderDetailBean);
		startActivity(intent);
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == OrderPresenter.OrderQuerySuccess) {
				orderDetailBean = (OrderDetailBean) entity.getData();
				Log.v("storeId", orderDetailBean.getStoreid() + "storeId");
				orderPresenter.getStoreFavourable(orderDetailBean.getStoreid());
				if (type.equals("3")) {// 待收货
					btn_1.setVisibility(View.GONE);
					btn_2.setVisibility(View.GONE);
					btn_3.setVisibility(View.GONE);
					dengdaipingjia.setText("买家已付款");
					if (orderDetailBean.getOrderStatus().equals("4")) {// 待收货
						jiaoyi_status.setText("待收货");
						btn_3.setVisibility(View.VISIBLE);
						btn_4.setVisibility(View.VISIBLE);
						// 底部按钮
						btn_3.setText("查看物流");
						btn_3.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(
										MainApplication.context,
										WebActivity.class);
								intent.putExtra("title", "物流查询");
								intent.putExtra("url",
										"http://api.moodwo.com/webview.php/express/viewOrder?order_code="
												+ orderCode + "&tpl=0");
								startActivity(intent);
							}
						});
						btn_5.setVisibility(View.VISIBLE);
						btn_5.setOnClickListener(new OnClickListener() {// 确认收货

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								orderPresenter.makesureOrder(uid, orderCode);
							}
						});
					} else if (orderDetailBean.getOrderStatus().equals("3")) {
						jiaoyi_status.setText("待发货");
						daishouhuo.setVisibility(View.VISIBLE);
						btn_1.setText("退货");
						kuaidistatus.setText("快递");

						// 中间的按钮
						btn_1.setText("退货");
						btn_2.setText("退款");

						btn_1.setVisibility(View.GONE);
						btn_2.setVisibility(View.GONE);
					}else if(orderDetailBean.getOrderStatus().equals("2")){
						if(orderDetailBean.getPayStatus().equals("0")){
							jiaoyi_status.setText("待付款");
						}else if(orderDetailBean.getPayStatus().equals("1")){
							jiaoyi_status.setText("已付款");
						}
						if(orderDetailBean.getCsStatus().equals("0")){
							jiaoyi_status.setText("未申请售后");
						}else if(orderDetailBean.getCsStatus().equals("2")){
							jiaoyi_status.setText("售后待处理");
						}else if(orderDetailBean.getCsStatus().equals("3")){
							jiaoyi_status.setText("售后已处理");
						}
					}
					btn_4.setText("申请售后");
					shengyutime.setVisibility(View.GONE);
					// 付款布局
					zhifu.setVisibility(View.VISIBLE);
				} else if (type.equals("5")) {
					// 付款布局
					zhifu.setVisibility(View.VISIBLE);

					shengyutime.setVisibility(View.GONE);
					jiaoyi_status.setText("待收货");

					daishouhuo.setVisibility(View.GONE);
				} else if (type.equals("6")) {
					jiaoyi_status.setText("交易成功");
					daishouhuo.setVisibility(View.GONE);
					dengdaipingjia.setText("交易成功");

					shengyutime.setVisibility(View.GONE);
					// 付款布局
					zhifu.setVisibility(View.VISIBLE);

					// 中部按钮
					btn_1.setVisibility(View.GONE);
					btn_2.setText("申请售后");
					// 底部按钮
					btn_3.setText("查看物流");
					btn_4.setText("评价");
				} else if (type.equals("1")) {
					daishouhuo.setVisibility(View.GONE);
					shengyutime.setVisibility(View.VISIBLE);
					dengdaipingjia.setText("等待买家付款");
					// 付款布局
					// zhifu.setVisibility(View.GONE);
					yuezhifu.setText("-￥" + orderDetailBean.getPayBalance());
					// 中部按钮
					btn_1.setVisibility(View.GONE);
					btn_2.setVisibility(View.GONE);
					// 底部按钮

					btn_3.setText("取消订单");
					btn_4.setText("去支付");
				}
				orderCode = orderDetailBean.getOrderCode();
				shengyutime.setText("剩余支付时间");
				mobile.setText(orderDetailBean.getMobile());
				txt_reciever.setText("收件人:" + orderDetailBean.getContactname());
				address.setText("收货地址：" + orderDetailBean.getProvince()
						+ orderDetailBean.getCity() + orderDetailBean.getarea()
						+ orderDetailBean.getDetailinfo());
				goods_num.setText("共" + orderDetailBean.getItems().size()
						+ "件商品");
				for (int i = 0; i < orderDetailBean.getItems().size(); i++) {
					View view = LayoutInflater.from(DaiFuKuanDetail.this)
							.inflate(R.layout.goods_item, null);
					XImageLoader.load(GlobalConfig.API_URL
							+ "/picture/index?id="
							+ orderDetailBean.getItems().get(i).getImg(),
							((ImageView) view.findViewById(R.id.wait_pay_iv)));
					((TextView) view.findViewById(R.id.goodsname_tv))
							.setText(orderDetailBean.getItems().get(i)
									.getName());
					((TextView) view.findViewById(R.id.buy_num))
							.setText(orderDetailBean.getItems().get(i)
									.getSkuDesc());
					((TextView) view.findViewById(R.id.goods_price))
							.setText("￥"
									+ orderDetailBean.getItems().get(i)
											.getPrice());
					((TextView) view.findViewById(R.id.goods_old_price))
							.setText("￥"
									+ orderDetailBean.getItems().get(i)
											.getOriPrice());
					((TextView)view.findViewById(R.id.goods_old_price))
					.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线
					((TextView) view.findViewById(R.id.dangge_shuliang))
							.setText("x"
									+ orderDetailBean.getItems().get(i)
											.getCount());
					goodsPrice += Double.parseDouble(orderDetailBean.getItems()
							.get(i).getPrice())
							* Integer.parseInt(orderDetailBean.getCount());
					goods_container.addView(view);
				}
				yunfei.setText("(含运费￥" + orderDetailBean.getPostPrice() + ")");
				total_price.setText("￥"
						+ ParseDouble.getDouble((Double
								.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney()) + Double
								.parseDouble(orderDetailBean.getPostPrice())))
						+ "");
				total_price
						.setTag((Double.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney()) + Double
									.parseDouble(orderDetailBean.getPostPrice()))
								+ "");
				orderNo.setText(orderDetailBean.getOrderCode());
				finalJiage.setText("￥"
						+ ParseDouble.getDouble((Double
								.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney()) + Double
								.parseDouble(orderDetailBean.getPostPrice())))
						+ "");
				yunfei2.setText("￥" + orderDetailBean.getPostPrice());
				youhuiquan
						.setText(orderDetailBean.getCouponMoney() == null ? "无"
								: "-￥" + orderDetailBean.getCouponMoney());
				hongbao.setText(orderDetailBean.getRed_envelop_money() == null ? "无"
						: "-￥" + orderDetailBean.getRed_envelop_money());
				setUpTime
						.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
								.format(Long.parseLong(orderDetailBean
										.getCreatetime()) * 1000));
				if (orderDetailBean.getPayType().equals("2")) {
					zhifubao_txt.setText("微信支付");
				} else if (orderDetailBean.getPayType().equals("1")) {
					zhifubao_txt.setText("支付宝支付");
				}
				goodstotalprice.setText("￥" + ParseDouble.getDouble((Double
						.parseDouble(orderDetailBean.getPrice())
						)));
				zhifubaozhifu.setText("￥"
						+ ParseDouble.getDouble((Double
								.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney())
								+ Double.parseDouble(orderDetailBean
										.getPostPrice()) - Double
								.parseDouble(orderDetailBean.getPayBalance())))
						+ "");
				shifukuan.setText("￥"
						+ ParseDouble.getDouble((Double
								.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney())
								+ Double.parseDouble(orderDetailBean
										.getPostPrice()) - Double
								.parseDouble(orderDetailBean.getPayBalance())))
						+ "");
				shifukuan
						.setTag((Double.parseDouble(orderDetailBean.getPrice())
								- Double.parseDouble(orderDetailBean
										.getDiscountMoney())
								+ Double.parseDouble(orderDetailBean
										.getPostPrice()) - Double
									.parseDouble(orderDetailBean
											.getPayBalance()))
								+ "");
				yuezhifu.setText("￥" + orderDetailBean.getPayBalance());
				lianxikefu.setText(orderDetailBean.getServicePhone());
				mobile_rel.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent2 = new Intent();
						intent2.setAction(Intent.ACTION_CALL);
						intent2.setData(Uri.parse("tel:"
								+ orderDetailBean.getServicePhone()));
						// 开启系统拨号器
						startActivity(intent2);
					}
				});
			} else if (entity.getEventType() == OrderPresenter.OrderQueryFail) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == OrderPresenter.OrderDeleteSuccess) {
				ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderDeleteSuccess) {
				ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderDeleteFail) {
				ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderSureSuccess) {
				ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == OrderPresenter.OrderSureFail) {
				ByAlert.alert(entity.getData() + "");
				finish();
			} else if (entity.getEventType() == OrderPresenter.getFavourableSuccess) {
				storeBean = (StoreFavourableBean) entity.getData();
				if (Double.parseDouble(storeBean.getCondition()) <= Double
						.parseDouble(orderDetailBean.getPrice()))
					dianpu.setText("-￥" + storeBean.getDicountMoney());
				else
					dianpu.setText("无");
			} else if (entity.getEventType() == OrderPresenter.getFavourableFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/***
	 * 查看物流
	 */
	public void goToWebActivity() {
		Intent intent = new Intent(DaiFuKuanDetail.this, WebActivity.class);
		intent.putExtra("url", SpPublicParams.Logistics_URL + orderCode);
		startActivity(intent);
	}

	/***
	 * 调转支付界面
	 */
	public void goToPayActivity() {
		Intent intent = new Intent(DaiFuKuanDetail.this, PayTypeActivity.class);
		intent.putExtra("orderCode", orderCode);
		intent.putExtra("price", shifukuan.getTag().toString());
		intent.putExtra("desc", orderDetailBean.getStoreDesc());
		startActivity(intent);
		finish();
	}
}
